from django.shortcuts import HttpResponse, render, redirect
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsModelForm,LoginForm
from django.http import JsonResponse
from web import models
import uuid
import datetime
from django.core.exceptions import ValidationError

def register(request):
    """注册"""
    if request.method == "GET":
        form = RegisterModelForm()
        return render(request, "register.html", {"form": form})
    # print(request.POST)  # <QueryDict: {'csrfmiddlewaretoken': ['8AmVGsVuiSzVfdZffp9VqCJLZC7qET5f75MA9qtbxjR4e5rhveuZ3n4GzbmqPxlS'], 'username': ['wupeiqi'], 'email': ['123@qq.com'], 'password': [''], 'confirm_password': [''], 'mobile_phone': [''], 'code': ['']}>
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 如果验证成功，将用户信息写入数据库,而且写入的同时会返回一个instance
        # instance = form.save(), 相当于 instance = models.UserInfo.objects.create(**form.cleaned_data)
        # 会自动踢出数据库表中没有的字段
        instance = form.save()
        ## 用户注册成功后，为用户添加免费额度的交易记录
        policy_obj = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            status=1,
            order=str(uuid.uuid4()),
            user=instance,  # 等于当前注册成功的用户对象
            price_policy=policy_obj,  # 等于免费的价格策略
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True, "data": "/login/"})
    else:
        return JsonResponse({"status": False, "error": form.errors})


def send_sms(request):
    """发送短信"""
    print(request.GET)
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})

## 短信登陆
def login_sms(request):
    """短信登陆"""
    if request.method == "GET":
        form = LoginSmsModelForm()
        return render(request, "login_sms.html", {"form": form})
    form = LoginSmsModelForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data.get("mobile_phone")
        # 根据mobile_phone去拿到user_obj
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        # 把用户名写入到session中,并设置超时时间
        request.session["user_id"] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({"status": True, "data": "/index/"})
    return JsonResponse({"status": False, "error": form.errors})

def login(request):
    if request.method == "GET":
        form = LoginForm(request,)
        return render(request, "login.html", {"form": form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        print(username,password)
        # 通过手机号或邮箱和密码进行登录
        # (手机=username or 邮箱=username) and password=password
        # user_obj = models.UserInfo.objects.filter(username=username,
        #                                           password=password).first()
        from django.db.models import Q
        user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
                    password=password).first()
        print(user_obj)

        if user_obj:   # 用户名密码校验正确
            # 登录成功，将用户id写入到session中，并设置超时时间

            request.session["user_id"] = user_obj.id
            request.session.set_expiry(60*60*24*14)
            return redirect("/index")
        else:
            raise ValidationError("用户名或密码错误，请重新输入")
    return render(request, "login.html", {"form": form})

def image_code(request):
    """生成图片验证码"""
    from utils.img_code import check_code
    from io import BytesIO
    # 返回图片对象和验证码
    image_obj, code = check_code()
    #  将验证码保存到session中
    request.session["image_code"] = code
    # 为session设置过期时间,时间单位为秒
    request.session.set_expiry(60)
    # 将图片存储在内存中
    stream = BytesIO()
    image_obj.save(stream, "png")
    return HttpResponse(stream.getvalue())

## 退出
def logout(request):
    request.session.flush()   #把session中得数据进行清空
    return redirect("/index")

